package com.yun.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yun.mapper.UserMapper;
import com.yun.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class LoginService  implements UserDetailsService{
    @Autowired
    UserMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> wrapper = new QueryWrapper();
        wrapper.eq("username",username);
        Users users = usersMapper.selectOne(wrapper);
        if(users == null) {  throw new UsernameNotFoundException("用户名不存在！");  }
        System.out.println(users);
        //获取到用户的角色和权限
      List<String> roles=  usersMapper.selectRole(users.getId());

        List<String> menus= usersMapper.selectMenu(users.getId());
        List<GrantedAuthority> lists=new ArrayList<>();
        //处理角色
      for(String role:roles){
          SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority("ROLE_"+role);
          lists.add(simpleGrantedAuthority);
      }

      //处理权限
        for(String menu:menus){
          lists.add(new SimpleGrantedAuthority(menu));

        }

        String encode = new BCryptPasswordEncoder().encode(users.getPassword());
        System.out.println(encode);
/*
        List<GrantedAuthority> auths =  AuthorityUtils.commaSeparatedStringToAuthorityList("role,admin,ROLE_role1");*/
        return new User(users.getUsername(), encode,lists);
    }
}
